package com.df.agent.plugin.impl.link;

import com.df.agent.track.Span;
import com.df.agent.track.TrackContext;
import com.df.agent.track.TrackManager;
import net.bytebuddy.asm.Advice;


import java.util.UUID;

public class LinkAdvice {
    @Advice.OnMethodEnter()
    public static void enter(@Advice.This Object o, @Advice.Origin("#t") String className,
                             @Advice.Origin("#m") String methodName) {
        Span currentSpan = TrackManager.getCurrentSpan();
        if (null == currentSpan) {
            if(!methodName.equals("doAction")){
                return;
            }
            TrackContext.setTrackDeep(0);
            TrackContext.setFunctionId(1);
            String linkId = UUID.randomUUID().toString();
            TrackContext.setLinkId(linkId);
            currentSpan = TrackManager.createEntrySpan();
            currentSpan.setMethodName(methodName);
        }
        if(!currentSpan.getMethodName().equals(methodName)){
            currentSpan = TrackManager.createEntrySpan();
        }
        if(currentSpan==null) return;

        currentSpan.setTimes(currentSpan.getTimes()+1);
        currentSpan.setMethodName(methodName);
        currentSpan.setDeep(TrackContext.getTrackDeep());
        currentSpan.setOwnId(TrackContext.getFunctionId());
    }
    @Advice.OnMethodExit()
    public static void exit(@Advice.Origin("#t") String className,
                            @Advice.Origin("#m") String methodName) {
//        System.out.println(Thread.currentThread());
        Span exitSpan = TrackManager.getExitSpan();
        if (null == exitSpan) return;
        System.out.println("链路追踪(MQ)：" + exitSpan.getLinkId() + " " +
                className + "." + methodName + " 耗时：" + (System.nanoTime() -
                exitSpan.getEnterNamiao()) + "ns");
    }

    @Override
    public String toString() {
        return "advice";
    }
}
